<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Expeditionary - 移动版</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary-color: #3a5ec7;
            --secondary-color: #6c757d;
            --success-color: #28a745;
            --danger-color: #dc3545;
            --warning-color: #ffc107;
            --info-color: #17a2b8;
            --light-bg: #f8f9fa;
            --dark-bg: #343a40;
            --card-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f0f2f5;
            color: #333;
            padding-bottom: 70px;
        }

        .header {
            background: linear-gradient(135deg, var(--primary-color), #2c4aad);
            color: white;
            padding: 15px 0;
            border-radius: 0 0 15px 15px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }

        .player-card {
            background: white;
            border-radius: 12px;
            box-shadow: var(--card-shadow);
            margin-bottom: 15px;
            overflow: hidden;
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }

        .player-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 15px rgba(0,0,0,0.12);
        }

        .card-header {
            background: linear-gradient(to right, #4a6fd8, #3a5ec7);
            color: white;
            padding: 12px 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .status-badge {
            font-size: 0.75rem;
            padding: 4px 10px;
            border-radius: 20px;
            font-weight: 600;
        }

        .card-body {
            padding: 15px;
        }

        .info-item {
            display: flex;
            margin-bottom: 10px;
            align-items: flex-start;
        }

        .info-label {
            font-weight: 600;
            min-width: 90px;
            color: #555;
        }

        .info-value {
            flex: 1;
            word-break: break-word;
        }

        .badge-container {
            display: flex;
            flex-wrap: wrap;
            gap: 5px;
        }

        .badge {
            font-size: 0.75rem;
            padding: 5px 10px;
            border-radius: 15px;
            font-weight: 500;
        }

        .action-buttons {
            display: flex;
            gap: 8px;
            margin-top: 15px;
        }

        .btn-action {
            flex: 1;
            border-radius: 8px;
            font-weight: 500;
            padding: 8px 12px;
        }

        .floating-btn {
            position: fixed;
            bottom: 80px;
            right: 20px;
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: var(--primary-color);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 4px 12px rgba(0,0,0,0.2);
            z-index: 1000;
            font-size: 24px;
        }

        .filter-bar {
            background: white;
            padding: 15px;
            border-radius: 12px;
            box-shadow: var(--card-shadow);
            margin-bottom: 20px;
        }

        .section-title {
            font-size: 1.1rem;
            font-weight: 600;
            color: var(--primary-color);
            margin-bottom: 15px;
            padding-bottom: 8px;
            border-bottom: 2px solid #eaeaea;
        }

        .modal-content {
            border-radius: 15px;
            border: none;
        }

        .modal-header {
            background: linear-gradient(to right, #4a6fd8, #3a5ec7);
            color: white;
            border-radius: 15px 15px 0 0;
        }

        .form-label {
            font-weight: 500;
            color: #444;
            margin-bottom: 5px;
        }

        .select-hint {
            font-size: 0.8rem;
            color: #6c757d;
            margin-top: 5px;
        }

        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: #6c757d;
        }

        .empty-state i {
            font-size: 3rem;
            margin-bottom: 15px;
            color: #ced4da;
        }

        @media (max-width: 576px) {
            .info-item {
                flex-direction: column;
                margin-bottom: 12px;
            }

            .info-label {
                margin-bottom: 3px;
            }

            .btn-action {
                font-size: 0.85rem;
                padding: 6px 10px;
            }
        }
    </style>
</head>
<body>
<!-- 顶部标题栏 -->
<div class="header">
    <div class="container">
        <div class="d-flex justify-content-between align-items-center">
            <div>
                <h1 class="h4 mb-0">Expeditionary</h1>
                <p class="mb-0 opacity-75">开荒队成员列表</p>
            </div>
            <div class="d-flex align-items-center">
                <button class="btn btn-sm btn-light me-2" onclick="toggleFilters()">
                    <i class="fas fa-filter"></i>
                </button>
                <div class="form-check form-switch">
                    <input class="form-check-input" type="checkbox" id="onlineOnlyToggle">
                    <label class="form-check-label text-light" for="onlineOnlyToggle">仅在线</label>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="container">
    <!-- 筛选栏 -->
    <div class="filter-bar mb-3" id="filterBar" style="display: none;">
        <div class="section-title">筛选条件</div>
        <div class="row g-2">
            <div class="col-12">
                <input type="text" class="form-control" placeholder="搜索玩家名称或备注..." id="searchInput">
            </div>
            <div class="col-6">
                <select class="form-select" id="roleFilter">
                    <option value="">所有职能</option>
                    <option value="防护职业">防护职业</option>
                    <option value="纯粹治疗职业">纯粹治疗职业</option>
                    <option value="护罩治疗职业">护罩治疗职业</option>
                    <option value="近战职业">近战职业</option>
                    <option value="远程物理职业">远程物理职业</option>
                    <option value="远程魔法职业">远程魔法职业</option>
                </select>
            </div>
            <div class="col-6">
                <select class="form-select" id="dungeonFilter">
                    <option value="">所有副本</option>
                    <option value="幻巧战">幻巧战</option>
                    <option value="极神">极神</option>
                    <option value="零式">零式</option>
                    <option value="绝境战">绝境战</option>
                </select>
            </div>
            <div class="col-12">
                <button class="btn btn-primary w-100" onclick="applyFilters()">应用筛选</button>
            </div>
        </div>
    </div>

    <!-- 玩家卡片容器 -->
    <div id="playersContainer">
        <div class="text-center py-4">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
            <p class="mt-2">正在加载数据...</p>
        </div>
    </div>
</div>

<!-- 悬浮添加按钮 -->
<div class="floating-btn" data-bs-toggle="modal" data-bs-target="#addModal">
    <i class="fas fa-plus"></i>
</div>

<!-- 新增记录模态框 -->
<div class="modal fade" id="addModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">新增记录</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="addRowForm">
                    <div class="mb-3">
                        <label for="name" class="form-label">玩家名称</label>
                        <input type="text" class="form-control" id="name" name="name" required>
                    </div>
                    <div class="row">
                        <div class="col-6 mb-3">
                            <label for="free_start_time" class="form-label">开始时间</label>
                            <input type="time" class="form-control" id="free_start_time" name="free_start_time">
                        </div>
                        <div class="col-6 mb-3">
                            <label for="free_end_time" class="form-label">结束时间</label>
                            <input type="time" class="form-control" id="free_end_time" name="free_end_time">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="occupation" class="form-label">职能</label>
                        <select class="form-select" id="occupation" name="occupation" multiple size="3">
                            <option value="防护职业">防护职业/Tank</option>
                            <option value="纯粹治疗职业">纯粹治疗职业/Healer</option>
                            <option value="护罩治疗职业">护罩治疗职业/Healer with Shield</option>
                            <option value="近战职业">近战职业/Melee</option>
                            <option value="远程物理职业">远程物理职业/Ranged Physical</option>
                            <option value="远程魔法职业">远程魔法职业/Ranged Magic</option>
                        </select>
                        <div class="select-hint">按住Ctrl可以多选</div>
                    </div>
                    <div class="mb-3">
                        <label for="volunteer_dungeon" class="form-label">志愿副本</label>
                        <select class="form-select" id="volunteer_dungeon" name="volunteer_dungeon" multiple size="3">
                            <option value="幻巧战">幻巧战</option>
                            <option value="极神(旧版本)">极神(旧版本)</option>
                            <option value="极神(当前版本)">极神(当前版本)</option>
                            <option value="零式(旧版本)">零式(旧版本)</option>
                            <option value="零式(当前版本)">零式(当前版本)</option>
                            <option value="暗黑之云诛灭战">暗黑之云诛灭战</option>
                            <option value="巴哈姆特绝境战">巴哈姆特绝境战</option>
                            <option value="究极神兵绝境战">究极神兵绝境战</option>
                            <option value="亚历山大绝境战">亚历山大绝境战</option>
                            <option value="幻想龙诗绝境战">幻想龙诗绝境战</option>
                            <option value="欧米茄绝境验证战">欧米茄绝境验证战</option>
                            <option value="光暗未来绝境战">光暗未来绝境战</option>
                        </select>
                        <div class="select-hint">按住Ctrl可以多选</div>
                    </div>
                    <div class="row">
                        <div class="col-6 mb-3">
                            <label for="level" class="form-label">等级</label>
                            <input type="number" class="form-control" id="level" name="level" min="1" max="100">
                        </div>
                        <div class="col-6 mb-3">
                            <label for="guild_name" class="form-label">部队</label>
                            <input type="text" class="form-control" id="guild_name" name="guild_name" value="Phantom">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="notes" class="form-label">备注</label>
                        <textarea class="form-control" id="notes" name="notes" rows="2"></textarea>
                    </div>
                    <div class="mb-3 form-check form-switch">
                        <input type="checkbox" class="form-check-input" id="online_status" name="online_status" checked>
                        <label for="online_status" class="form-check-label">可用状态</label>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="addNewPlayer()">添加</button>
            </div>
        </div>
    </div>
</div>

<!-- 编辑记录模态框 -->
<div class="modal fade" id="editModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">编辑记录</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="editRowForm">
                    <input type="hidden" id="edit_uuid" name="uuid">
                    <div class="mb-3">
                        <label for="edit_name" class="form-label">玩家名称</label>
                        <input type="text" class="form-control" id="edit_name" name="name" required>
                    </div>
                    <div class="row">
                        <div class="col-6 mb-3">
                            <label for="edit_free_start_time" class="form-label">开始时间</label>
                            <input type="time" class="form-control" id="edit_free_start_time" name="free_start_time">
                        </div>
                        <div class="col-6 mb-3">
                            <label for="edit_free_end_time" class="form-label">结束时间</label>
                            <input type="time" class="form-control" id="edit_free_end_time" name="free_end_time">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="edit_occupation" class="form-label">职能</label>
                        <select class="form-select" id="edit_occupation" name="occupation" multiple size="3">
                            <option value="防护职业">防护职业/Tank</option>
                            <option value="纯粹治疗职业">纯粹治疗职业/Healer</option>
                            <option value="护罩治疗职业">护罩治疗职业/Healer with Shield</option>
                            <option value="近战职业">近战职业/Melee</option>
                            <option value="远程物理职业">远程物理职业/Ranged Physical</option>
                            <option value="远程魔法职业">远程魔法职业/Ranged Magic</option>
                        </select>
                        <div class="select-hint">按住Ctrl可以多选</div>
                    </div>
                    <div class="mb-3">
                        <label for="edit_volunteer_dungeon" class="form-label">志愿副本</label>
                        <select class="form-select" id="edit_volunteer_dungeon" name="volunteer_dungeon" multiple size="3">
                            <option value="幻巧战">幻巧战</option>
                            <option value="极神(旧版本)">极神(旧版本)</option>
                            <option value="极神(当前版本)">极神(当前版本)</option>
                            <option value="零式(旧版本)">零式(旧版本)</option>
                            <option value="零式(当前版本)">零式(当前版本)</option>
                            <option value="暗黑之云诛灭战">暗黑之云诛灭战</option>
                            <option value="巴哈姆特绝境战">巴哈姆特绝境战</option>
                            <option value="究极神兵绝境战">究极神兵绝境战</option>
                            <option value="亚历山大绝境战">亚历山大绝境战</option>
                            <option value="幻想龙诗绝境战">幻想龙诗绝境战</option>
                            <option value="欧米茄绝境验证战">欧米茄绝境验证战</option>
                            <option value="光暗未来绝境战">光暗未来绝境战</option>
                        </select>
                        <div class="select-hint">按住Ctrl可以多选</div>
                    </div>
                    <div class="row">
                        <div class="col-6 mb-3">
                            <label for="edit_level" class="form-label">等级</label>
                            <input type="number" class="form-control" id="edit_level" name="level" min="1" max="100">
                        </div>
                        <div class="col-6 mb-3">
                            <label for="edit_guild_name" class="form-label">部队</label>
                            <input type="text" class="form-control" id="edit_guild_name" name="guild_name">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="edit_notes" class="form-label">备注</label>
                        <textarea class="form-control" id="edit_notes" name="notes" rows="2"></textarea>
                    </div>
                    <div class="mb-3 form-check form-switch">
                        <input type="checkbox" class="form-check-input" id="edit_online_status" name="online_status">
                        <label for="edit_online_status" class="form-check-label">可用状态</label>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger me-auto" onclick="deletePlayer()">删除</button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="updatePlayer()">更新</button>
            </div>
        </div>
    </div>
</div>

<!-- Bootstrap & jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<script>
    // 配置信息
    const config = {
        apiKey: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRzaG1ic2F3d3JidXljbml2Y2pzIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTM5Mjg2OTAsImV4cCI6MjA2OTUwNDY5MH0.fwRJD-WuST7mCbJf9h2i2Xk0z6mtCMCeV--JGUecC6A',
        authorization: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRzaG1ic2F3d3JidXljbml2Y2pzIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTM5Mjg2OTAsImV4cCI6MjA2OTUwNDY5MH0.fwRJD-WuST7mCbJf9h2i2Xk0z6mtCMCeV--JGUecC6A',
        prefer: 'return=minimal',
        baseUrl: 'https://dshmbsawwrbuycnivcjs.supabase.co/rest/v1'
    };

    // 页面加载时获取数据
    document.addEventListener('DOMContentLoaded', function() {
        fetchPlayers();
        setupEventListeners();
    });

    // 设置事件监听器
    function setupEventListeners() {
        // 在线状态切换
        document.getElementById('onlineOnlyToggle').addEventListener('change', function() {
            applyFilters();
        });

        // 搜索输入框
        document.getElementById('searchInput').addEventListener('input', function() {
            applyFilters();
        });

        // 角色筛选
        document.getElementById('roleFilter').addEventListener('change', function() {
            applyFilters();
        });

        // 副本筛选
        document.getElementById('dungeonFilter').addEventListener('change', function() {
            applyFilters();
        });
    }

    // 获取玩家数据
    function fetchPlayers() {
        fetch(`${config.baseUrl}/expeditionary_team?select=*`, {
            method: 'GET',
            headers: {
                'apikey': config.apiKey,
                'Authorization': config.authorization
            }
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                return response.json();
            })
            .then(data => {
                window.allPlayers = data;
                renderPlayers(data);
            })
            .catch(error => {
                console.error('获取数据错误:', error);
                showMessage('获取数据失败: ' + error.message, 'error');
            });
    }

    // 渲染玩家卡片
    function renderPlayers(playersData) {
        const container = document.getElementById('playersContainer');

        if (playersData.length === 0) {
            container.innerHTML = `
                    <div class="empty-state">
                        <i class="fas fa-users"></i>
                        <h5>没有找到玩家</h5>
                        <p>尝试调整筛选条件或添加新玩家</p>
                    </div>
                `;
            return;
        }

        let html = '';

        playersData.forEach(player => {
            // 格式化多选字段的显示
            const occupationDisplay = player.occupation ? player.occupation.split(',').map(item =>
                `<span class="badge bg-primary">${item.trim()}</span>`).join(' ') : '';

            const dungeonDisplay = player.volunteer_dungeon ? player.volunteer_dungeon.split(',').map(item =>
                `<span class="badge bg-info text-dark">${item.trim()}</span>`).join(' ') : '';

            const statusClass = player.online_status ? 'bg-success' : 'bg-secondary';
            const statusText = player.online_status ? '在线' : '离线';

            html += `
                    <div class="player-card" data-uuid="${player.uuid}">
                        <div class="card-header">
                            <span>${player.name || '未命名'}</span>
                            <span class="status-badge ${statusClass}">${statusText}</span>
                        </div>
                        <div class="card-body">
                            <div class="info-item">
                                <span class="info-label">在线时间:</span>
                                <span class="info-value">${player.free_start_time || '-'} - ${player.free_end_time || '-'}</span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">职能:</span>
                                <span class="info-value">
                                    <div class="badge-container">
                                        ${occupationDisplay || '无'}
                                    </div>
                                </span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">志愿副本:</span>
                                <span class="info-value">
                                    <div class="badge-container">
                                        ${dungeonDisplay || '无'}
                                    </div>
                                </span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">等级/部队:</span>
                                <span class="info-value">${player.level || '-'} / ${player.guild_name || '-'}</span>
                            </div>
                            ${player.notes ? `
                            <div class="info-item">
                                <span class="info-label">备注:</span>
                                <span class="info-value">${player.notes}</span>
                            </div>
                            ` : ''}
                            <div class="action-buttons">
                                <button class="btn btn-action btn-outline-primary" onclick="editPlayer('${player.uuid}')">
                                    <i class="fas fa-edit me-1"></i>编辑
                                </button>
                                <button class="btn btn-action btn-outline-${player.online_status ? 'secondary' : 'success'}" onclick="toggleStatus('${player.uuid}')">
                                    <i class="fas ${player.online_status ? 'fa-toggle-off' : 'fa-toggle-on'} me-1"></i>${player.online_status ? '设为离线' : '设在线'}
                                </button>
                            </div>
                        </div>
                    </div>
                `;
        });

        container.innerHTML = html;
    }

    // 应用筛选条件
    function applyFilters() {
        if (!window.allPlayers) return;

        const searchText = document.getElementById('searchInput').value.toLowerCase();
        const roleFilter = document.getElementById('roleFilter').value;
        const dungeonFilter = document.getElementById('dungeonFilter').value;
        const onlineOnly = document.getElementById('onlineOnlyToggle').checked;

        const filteredPlayers = window.allPlayers.filter(player => {
            // 搜索文本过滤
            const matchesSearch = searchText === '' ||
                (player.name && player.name.toLowerCase().includes(searchText)) ||
                (player.notes && player.notes.toLowerCase().includes(searchText));

            // 职能过滤
            const matchesRole = roleFilter === '' ||
                (player.occupation && player.occupation.includes(roleFilter));

            // 副本过滤
            const matchesDungeon = dungeonFilter === '' ||
                (player.volunteer_dungeon && player.volunteer_dungeon.includes(dungeonFilter));

            // 在线状态过滤
            const matchesOnline = !onlineOnly || player.online_status;

            return matchesSearch && matchesRole && matchesDungeon && matchesOnline;
        });

        renderPlayers(filteredPlayers);
    }

    // 切换筛选栏显示
    function toggleFilters() {
        const filterBar = document.getElementById('filterBar');
        filterBar.style.display = filterBar.style.display === 'none' ? 'block' : 'none';
    }

    // 显示消息
    function showMessage(message, type) {
        // 创建消息Toast
        const toast = document.createElement('div');
        toast.className = `position-fixed bottom-0 start-50 translate-middle-x p-3`;
        toast.style.zIndex = '1100';

        toast.innerHTML = `
                <div class="toast align-items-center text-white bg-${type === 'error' ? 'danger' : 'success'} border-0 show" role="alert">
                    <div class="d-flex">
                        <div class="toast-body">
                            ${message}
                        </div>
                        <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                    </div>
                </div>
            `;

        document.body.appendChild(toast);

        // 5秒后移除消息
        setTimeout(() => {
            toast.remove();
        }, 5000);
    }

    // 添加新玩家
    function addNewPlayer() {
        const form = document.getElementById('addRowForm');
        const formData = new FormData(form);

        const newPlayer = {
            uuid: generateUUID(),
            name: formData.get('name'),
            free_start_time: formData.get('free_start_time'),
            free_end_time: formData.get('free_end_time'),
            occupation: Array.from(document.getElementById('occupation').selectedOptions)
                .map(option => option.value).join(', '),
            volunteer_dungeon: Array.from(document.getElementById('volunteer_dungeon').selectedOptions)
                .map(option => option.value).join(', '),
            level: formData.get('level'),
            guild_name: formData.get('guild_name'),
            notes: formData.get('notes'),
            online_status: document.getElementById('online_status').checked
        };

        fetch(`${config.baseUrl}/expeditionary_team`, {
            method: 'POST',
            headers: {
                'apikey': config.apiKey,
                'Authorization': config.authorization,
                'Content-Type': 'application/json',
                'Prefer': 'return=representation'
            },
            body: JSON.stringify(newPlayer)
        })
            .then(response => {
                if (response.ok) {
                    return response.json();
                }
                throw new Error('添加记录失败');
            })
            .then(data => {
                $('#addModal').modal('hide');
                form.reset();
                fetchPlayers();
                showMessage('玩家添加成功!', 'success');
            })
            .catch(error => {
                console.error('添加记录错误:', error);
                showMessage('添加记录失败: ' + error.message, 'error');
            });
    }

    // 编辑玩家
    function editPlayer(uuid) {
        fetch(`${config.baseUrl}/expeditionary_team?uuid=eq.${uuid}`, {
            method: 'GET',
            headers: {
                'apikey': config.apiKey,
                'Authorization': config.authorization
            }
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                return response.json();
            })
            .then(data => {
                if (data.length > 0) {
                    const player = data[0];

                    // 填充表单数据
                    document.getElementById('edit_uuid').value = player.uuid;
                    document.getElementById('edit_name').value = player.name || '';
                    document.getElementById('edit_free_start_time').value = player.free_start_time || '';
                    document.getElementById('edit_free_end_time').value = player.free_end_time || '';
                    document.getElementById('edit_level').value = player.level || '';
                    document.getElementById('edit_guild_name').value = player.guild_name || '';
                    document.getElementById('edit_notes').value = player.notes || '';
                    document.getElementById('edit_online_status').checked = player.online_status || false;

                    // 处理多选字段
                    if (player.occupation) {
                        const occupations = player.occupation.split(',').map(item => item.trim());
                        const occupationSelect = document.getElementById('edit_occupation');
                        Array.from(occupationSelect.options).forEach(option => {
                            option.selected = occupations.includes(option.value);
                        });
                    }

                    if (player.volunteer_dungeon) {
                        const dungeons = player.volunteer_dungeon.split(',').map(item => item.trim());
                        const dungeonSelect = document.getElementById('edit_volunteer_dungeon');
                        Array.from(dungeonSelect.options).forEach(option => {
                            option.selected = dungeons.includes(option.value);
                        });
                    }

                    $('#editModal').modal('show');
                }
            })
            .catch(error => {
                console.error('获取玩家数据错误:', error);
                showMessage('获取玩家数据失败: ' + error.message, 'error');
            });
    }

    // 更新玩家信息
    function updatePlayer() {
        const form = document.getElementById('editRowForm');
        const formData = new FormData(form);
        const uuid = formData.get('uuid');

        const updatedPlayer = {
            name: formData.get('name'),
            free_start_time: formData.get('free_start_time'),
            free_end_time: formData.get('free_end_time'),
            occupation: Array.from(document.getElementById('edit_occupation').selectedOptions)
                .map(option => option.value).join(', '),
            volunteer_dungeon: Array.from(document.getElementById('edit_volunteer_dungeon').selectedOptions)
                .map(option => option.value).join(', '),
            level: formData.get('level'),
            guild_name: formData.get('guild_name'),
            notes: formData.get('notes'),
            online_status: document.getElementById('edit_online_status').checked
        };

        fetch(`${config.baseUrl}/expeditionary_team?uuid=eq.${uuid}`, {
            method: 'PATCH',
            headers: {
                'apikey': config.apiKey,
                'Authorization': config.authorization,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(updatedPlayer)
        })
            .then(response => {
                if (response.status === 204 || response.ok) {
                    $('#editModal').modal('hide');
                    fetchPlayers();
                    showMessage('玩家信息更新成功!', 'success');
                    return;
                }
                throw new Error('更新记录失败');
            })
            .catch(error => {
                console.error('更新记录错误:', error);
                showMessage('更新记录失败: ' + error.message, 'error');
            });
    }

    // 删除玩家
    function deletePlayer() {
        const uuid = document.getElementById('edit_uuid').value;

        if (!confirm('确定要删除这个玩家吗？此操作不可撤销。')) {
            return;
        }

        fetch(`${config.baseUrl}/expeditionary_team?uuid=eq.${uuid}`, {
            method: 'DELETE',
            headers: {
                'apikey': config.apiKey,
                'Authorization': config.authorization
            }
        })
            .then(response => {
                if (response.ok) {
                    $('#editModal').modal('hide');
                    fetchPlayers();
                    showMessage('玩家删除成功!', 'success');
                } else {
                    throw new Error('删除记录失败');
                }
            })
            .catch(error => {
                console.error('删除记录错误:', error);
                showMessage('删除记录失败: ' + error.message, 'error');
            });
    }

    // 切换玩家状态
    function toggleStatus(uuid) {
        const player = window.allPlayers.find(p => p.uuid === uuid);
        if (!player) return;

        const newStatus = !player.online_status;

        fetch(`${config.baseUrl}/expeditionary_team?uuid=eq.${uuid}`, {
            method: 'PATCH',
            headers: {
                'apikey': config.apiKey,
                'Authorization': config.authorization,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ online_status: newStatus })
        })
            .then(response => {
                if (response.status === 204 || response.ok) {
                    fetchPlayers();
                    showMessage(`玩家已${newStatus ? '上线' : '下线'}!`, 'success');
                    return;
                }
                throw new Error('更新状态失败');
            })
            .catch(error => {
                console.error('更新状态错误:', error);
                showMessage('更新状态失败: ' + error.message, 'error');
            });
    }

    // 生成UUID
    function generateUUID() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            const r = Math.random() * 16 | 0;
            const v = c === 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    }
</script>

<!-- 引入访客统计模块 -->
<script src="../visitor-tracker.js"></script>
<!-- Cloudflare Web Analytics -->
<script defer src='../lib/cloudflare/beacon.min.js' data-cf-beacon='{"token": "0e55e488041949479a3dace73ef940cd"}'>
</script>
<!-- End Cloudflare Web Analytics -->

</body>
</html>